package com.a2.appa3.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.Window;
import android.widget.Toast;

import com.a2.appa3.R;
import com.a2.appa3.dagger.component.activity.DaggerSplashActivityComponent;
import com.a2.appa3.dagger.module.activity.SplashActivityModule;
import com.a2.appa3.global.HttpAdress;
import com.a2.appa3.global.Info;
import com.a2.appa3.model.network.entity.req.ResURL;
import com.a2.appa3.presenter.activity.SplashActivityPresenter;
import com.a2.appa3.util.DisplayUtils;
import com.a2.appa3.util.SYSOUtils;
import com.a2.appa3.util.SpUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Administrator on 2017/8/4.
 * 启动页面
 */

public class SplashActivity extends BaseActivity<SplashActivityPresenter> implements EasyPermissions.PermissionCallbacks {

    List<String> urllist = new ArrayList<>();

    @Override
    protected void initDagger() {
        DaggerSplashActivityComponent.builder()
                .splashActivityModule(new SplashActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected int setContentView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);//这行代码一定要在setContentView之前，不然会闪退
        return R.layout.splash;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initS();
        mPresenter.test();
    }

    private void initview() {
        //声音和震动判断
        if (SpUtils.getBoolean(SplashActivity.this, "voiceswich")) {
            Info.voiceflag = true;
        } else {
            Info.voiceflag = false;
        }
        if (SpUtils.getBoolean(SplashActivity.this, "shockswich")) {
            Info.shockflag = true;
        } else {
            Info.shockflag = false;
        }
        //判断是否第一次开启应用
        Boolean isFirstOpen = SpUtils.getBoolean(this, getString(R.string.sp_key_firstOpen)/*Constants.FIRST_OPEN*/);
        //如果是第一次启动，进入功能引导页
        if (!true) {
            SYSOUtils.sOut_("第一次" + isFirstOpen);
        } else {
            SYSOUtils.sOut_("第二次" + isFirstOpen);
            //如果不是第一次启动，则正常显示启动屏
            setContentView(R.layout.splash);

//            String username = SpUtils.getString(this, "username");
//            String password = SpUtils.getString(this, "password");
//            HttpJsonUtils.getHttpApiInstance()
//                    .login(HttpAdress.getuseAdress() + "api/m/login", username, Md5.toMd5(password), Info.Token)
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new CustomObserver<ResLogin>() {
//                        @Override
//                        protected void onCustomNext(ResLogin resLogin) {
//                            try {
//                                if (resLogin.code == 0 && resLogin.data != null) {
//                                    Info.user = null;
//                                    Info.Token = null;
//                                    Info.user = resLogin.data;
//                                    Info.Token = resLogin.data.token;
//                                    SpUtils.clearUser(SplashActivity.this);
//                                    SpUtils.putString(SplashActivity.this, "User", new Gson().toJson(resLogin.data));
//                                    //这里通知更新数据
//                                    GOHOME();
//                                } else {
//                                    GOHOME();
//                                }
//                            } catch (Exception e) {
//                                GOHOME();
//                            }
//                        }
//
//                        @Override
//                        protected void onSubscribeCustom(Disposable disposable) {
//
//                        }
//
//                        @Override
//                        protected void onErrorCustom(Throwable e) {
//                            enterHomeActivty();
//                        }
//                    });
            GOHOME();
        }
    }

    private void GOHOME() {
        String[] ids = {Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE};
        requestPermission(this, "请同意以下权限以确保版本更新功能能够使用", 200, ids);
    }

    /**
     * 获取屏幕信息
     */
    private void initS() {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        Info.screenWidth = metric.widthPixels;
        Info.screenHeight = metric.heightPixels;
        Info.screenW = DisplayUtils.px2dip(this, Info.screenWidth);
        Info.screenH = DisplayUtils.px2dip(this, Info.screenHeight);
    }

    private void enterHomeActivty() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        getWindow().setBackgroundDrawable(null);//释放资源
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // EasyPermissions 权限处理请求结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 请求权限
     *
     * @param context
     */
    public void requestPermission(Activity context, String tip, int requestCode, String[] perms) {
        EasyPermissions.requestPermissions(context, tip, requestCode, perms);
    }

    //同意授权
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        enterHomeActivty();
    }

    //权限被拒
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Toast.makeText(this, "您拒绝了权限，将无法版本更新，如果需要版本更新功能，请到设置界面打开相应权限", Toast.LENGTH_LONG).show();
    }

    public void succsec(ResURL resURL) {
        for (int i = 0; i < resURL.chat.size(); i++) {
            try {
                String string = new String(Base64.decode((((String) resURL.chat.get(i))).getBytes(), Base64.DEFAULT));
                String text2 = java.net.URLDecoder.decode(string, "utf-8");
                SYSOUtils.sOut_("HUHU获取到的域名为" + text2);
//                urllist.add("https://www.ws88168.com/");
                urllist.add(text2 + "/");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (urllist.size() == 0) {
            Toast.makeText(SplashActivity.this, "当前无可用的域名", Toast.LENGTH_SHORT).show();
            return;
        } else {
            if (urllist.get(0).contains("m/#/home")) {
                String str = urllist.get(0).substring(0, urllist.get(0).indexOf("m/#"));
                SYSOUtils.sOut_("++++++++++++++++++++" + str);
                HttpAdress.adress = str;
                initview();
            } else {
                HttpAdress.adress = urllist.get(0).toString();
                initview();
            }
        }

    }
}
